package test.serializable ;

import java.io.File ;
import java.io.FileInputStream ;
import java.io.FileOutputStream ;
import java.io.IOException ;
import java.io.ObjectInputStream ;
import java.io.ObjectOutputStream ;

/**
 * 序列化工具类
 * @author 80002165 @date 2017年3月31日 上午11:29:45
 */
public class SerializableUtils {
    private final static String DEF_PATH = "E:/testjava/testFile/" ;
    
    protected static void writeToFile(Object serializableObj, String fileName) {
        writeToFile(serializableObj, DEF_PATH, fileName) ;
    }
    
    protected static void writeToFile(Object serializableObj, String path, String fileName) {
        try {
            ObjectOutputStream stream = new ObjectOutputStream(new FileOutputStream(new File(path + fileName))) ;
            stream.writeObject(serializableObj) ;
            stream.close() ;
        } catch (IOException e) {
            e.printStackTrace() ;
        }
    }
    
    protected static Object readFromFile(String fileName) throws ClassNotFoundException, IOException {
        return readFromFile(DEF_PATH, fileName) ;
    }
    
    protected static Object readFromFile(String path, String fileName) throws IOException, ClassNotFoundException {
        ObjectInputStream stream = null ;
        try {
            stream = new ObjectInputStream(new FileInputStream(new File(path + fileName))) ;
            return stream.readObject() ;
        } catch (IOException | ClassNotFoundException e) {
            throw e ;
        } finally {
            try {
                if (stream != null)
                    stream.close() ;
            } catch (IOException e) {
                e.printStackTrace() ;
            }
        }
        
    }
}
